#!/usr/bin/env python3
"""
SVG Horizontal Merger for Navigation Snapshots
横向拼接多张SVG图片的专用工具
"""

import svgwrite
import xml.etree.ElementTree as ET
import argparse
import os
from datetime import datetime

def parse_svg_size(svg_file):
    """解析SVG文件的尺寸"""
    tree = ET.parse(svg_file)
    root = tree.getroot()
    
    # 获取SVG的width和height属性
    width = root.get('width')
    height = root.get('height')
    
    if width and height:
        # 移除单位（如px）并转换为数字
        width = float(width.replace('px', ''))
        height = float(height.replace('px', ''))
        return width, height
    else:
        # 如果没有直接的width/height属性，尝试从viewBox获取
        viewbox = root.get('viewBox')
        if viewbox:
            parts = viewbox.split()
            if len(parts) >= 4:
                return float(parts[2]), float(parts[3])
    
    # 默认尺寸
    return 480, 480

def extract_svg_content(svg_file):
    """提取SVG文件的内容（除了根元素外的所有内容）"""
    tree = ET.parse(svg_file)
    root = tree.getroot()
    
    # 获取所有子元素
    content_elements = list(root)
    return content_elements

def merge_svgs_horizontal(svg_files, output_file, spacing=20):
    """横向拼接多张SVG图片"""
    if not svg_files:
        print("No SVG files provided!")
        return
    
    print(f"Merging {len(svg_files)} SVG files...")
    
    # 解析所有SVG文件的尺寸
    svg_info = []
    total_width = 0
    max_height = 0
    
    for svg_file in svg_files:
        if not os.path.exists(svg_file):
            print(f"Warning: File {svg_file} does not exist, skipping...")
            continue
            
        width, height = parse_svg_size(svg_file)
        content = extract_svg_content(svg_file)
        
        svg_info.append({
            'file': svg_file,
            'width': width,
            'height': height,
            'content': content,
            'x_offset': total_width
        })
        
        total_width += width + spacing
        max_height = max(max_height, height)
        
        print(f"  {os.path.basename(svg_file)}: {width}x{height}")
    
    # 移除最后一个spacing
    total_width -= spacing
    
    print(f"Total dimensions: {total_width}x{max_height}")
    
    # 直接手动构建SVG内容
    with open(output_file, 'w') as f:
        f.write(f'<?xml version="1.0" encoding="UTF-8"?>\n')
        f.write(f'<svg xmlns="http://www.w3.org/2000/svg" ')
        f.write(f'width="{total_width}" height="{max_height}" ')
        f.write(f'viewBox="0 0 {total_width} {max_height}">\n')
        
        # 添加每个SVG的内容
        for info in svg_info:
            f.write(f'  <g transform="translate({info["x_offset"]}, 0)">\n')
            
            # 使用XML解析器正确提取SVG内容
            tree = ET.parse(info['file'])
            root = tree.getroot()
            
            # 提取所有子元素（排除<defs />等空元素）
            for element in root:
                if element.tag.endswith('defs') and len(element) == 0:
                    continue  # 跳过空的defs元素
                
                # 将元素转换为字符串并添加适当的缩进
                element_str = ET.tostring(element, encoding='unicode', method='xml')
                # 添加缩进
                indented_lines = ['    ' + line for line in element_str.split('\n')]
                f.write('\n'.join(indented_lines))
                f.write('\n')
            
            f.write('  </g>\n')
        
        f.write('</svg>\n')
    
    print(f"Merged SVG saved to: {output_file}")
    return output_file

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='Horizontally merge multiple SVG files')
    parser.add_argument('svg_files', nargs='+', help='SVG files to merge')
    parser.add_argument('--output', '-o', type=str, 
                       default=None, help='Output SVG file (default: auto-generated)')
    parser.add_argument('--spacing', '-s', type=int, default=20, 
                       help='Spacing between SVG images (default: 20)')
    
    args = parser.parse_args()
    
    # 生成输出文件名（如果未指定）
    if args.output is None:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        args.output = f"./logs/merged_navigation_{timestamp}.svg"
    
    print("=" * 60)
    print("   SVG Horizontal Merger")
    print("   横向拼接SVG图片工具")
    print("=" * 60)
    print(f"Input files: {len(args.svg_files)}")
    for i, file in enumerate(args.svg_files, 1):
        print(f"  {i}. {file}")
    print(f"Output: {args.output}")
    print(f"Spacing: {args.spacing}px")
    print("-" * 60)
    
    # 执行拼接
    result_file = merge_svgs_horizontal(args.svg_files, args.output, args.spacing)
    
    print("-" * 60)
    print("Merge completed successfully!")
    print(f"Result saved to: {result_file}")

if __name__ == "__main__":
    main()
